<template>
  <div class="search-div">
    <!--搜索表单-->
    <el-form label-width="70px" size="small">
      <el-row>
        <el-col :span="12">
          <el-form-item label="品牌">
            <el-select
              class="m-2"
              v-model="productDto.brandId"
              placeholder="选择品牌"
              size="small"
              style="width: 100%"
            >
              <el-option
                v-for="item in brandList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分类">
            <el-cascader
              :props="categoryProps"
              style="width: 100%"
              v-model="searchCategoryIdList"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="display:flex">
        <el-button type="primary" size="small" @click="fetchData">
          搜索
        </el-button>
        <el-button size="small" @click="resetData">重置</el-button>
      </el-row>
    </el-form>
  </div>

  <div class="tools-div">
    <el-button type="success" size="small" @click="addShow">添 加</el-button>
  </div>
  <!--数据展示-->
  <el-table :data="list" style="width: 100%">
    <el-table-column
      prop="sliderUrls"
      label="轮播图"
      #default="scope"
      width="200"
    >
      <div style="height: 50px;float: left;">
        <img
          v-for="(item, index) in scope.row.sliderUrls.split(',')"
          :key="index"
          :src="item"
          width="50"
        />
      </div>
    </el-table-column>
    <el-table-column prop="name" label="商品名称" width="160" />
    <el-table-column prop="brandName" label="品牌" />
    <el-table-column prop="category1Name" label="一级分类" />
    <el-table-column prop="category2Name" label="二级分类" />
    <el-table-column prop="category3Name" label="三级分类" />
    <el-table-column prop="unitName" label="计量单位" />
    <el-table-column prop="status" label="状态" #default="scope">
      {{
        scope.row.status == 0
          ? '未上架'
          : scope.row.status == 1
          ? '上架'
          : '下架'
      }}
    </el-table-column>
    <el-table-column prop="auditStatus" label="审核状态" #default="scope">
      {{
        scope.row.auditStatus == 0
          ? '未审核'
          : scope.row.auditStatus == 1
          ? '通过'
          : '驳回'
      }}
    </el-table-column>
    <el-table-column label="操作" align="center" width="200" #default="scope">
      <el-button
        type="primary"
        size="small"
        @click="editShow(scope.row)"
        style="padding: 5px; margin-left: 5px;"
      >
        修改
      </el-button>
      <el-button
        type="danger"
        size="small"
        @click="remove(scope.row.id)"
        style="padding: 5px; margin-left: 5px;"
      >
        删除
      </el-button>
      <!--
        v-if="scope.row.auditStatus == 0 || scope.row.auditStatus == -1" 等于0(未审核)或-1(驳回) 都可以在进行审核
        等于 1(通过)
      -->
      <el-button
        v-if="scope.row.auditStatus == 0 || scope.row.auditStatus == -1"
        type="success"
        size="small"
        @click="audit(scope.row.id)"
        style="padding: 5px; margin-left: 5px;"
      >
        审批
      </el-button>
      <!--
            scope.row.auditStatus == 1(审核通过才可以进行商品上下架),
            scope.row.status == 0(初始值) scope.row.status == -1(下架)
      -->
      <el-button
        v-if="
          scope.row.auditStatus == 1 &&
            (scope.row.status == 0 || scope.row.status == -1) &&
            scope.row.status == 0
        "
        type="warning"
        size="small"
        @click="updateStatus(scope.row.id, 1)"
        style="padding: 5px; margin-left: 5px;"
      >
        上架
      </el-button>
      <!--
            scope.row.auditStatus == 1(审核通过才可以进行商品上下架),
            scope.row.status == 0(初始值) scope.row.status == 1(上架)
      -->
      <el-button
        v-if="
          scope.row.auditStatus == 1 &&
            (scope.row.status == 0 || scope.row.status == 1) &&
            scope.row.status == 1
        "
        type="warning"
        plain
        size="small"
        @click="updateStatus(scope.row.id, -1)"
        style="padding: 5px; margin-left: 5px;"
      >
        下架
      </el-button>
    </el-table-column>
  </el-table>
  <!--添加和修改弹窗---->
  <el-dialog v-model="dialogVisible" :title="title" width="80%">
    <el-form
      label-width="120px"
      style="margin-top: 10px;"
      :label-position="labelPosition"
    >
      <el-collapse v-model="activeNames">
        <el-collapse-item title="商品基本信息" name="productBaseInfo">
          <el-form-item label="商品名称">
            <el-input v-model="product.name" />
          </el-form-item>
          <el-form-item label="分类">
            <el-cascader
              style="width: 100%;"
              :props="categoryProps"
              v-model="product.categoryIdList"
              @change="categoryChange"
            />
          </el-form-item>
          <el-form-item label="品牌">
            <el-select
              class="m-2"
              placeholder="选择品牌"
              v-model="product.brandId"
              style="width: 100%;"
            >
              <el-option
                v-for="item in categoryBrandList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商品单元">
            <el-select
              v-model="product.unitName"
              style="width: 100%;"
              class="m-2"
              placeholder="商品单元"
            >
              <el-option
                v-for="item in productUnitList"
                :key="item.id"
                :label="item.name"
                :value="item.name"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="轮播图">
            <el-upload
              v-model:file-list="fileList"
              action="http://localhost:8200/api/minio/fileUpload"
              list-type="picture-card"
              multiple
              :on-success="handleSliderSuccess"
              :on-remove="handleRemove"
              :headers="headers"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-collapse-item>

        <el-collapse-item title="商品SKU信息" name="skuInfo">
          <el-form-item label="选择规格">
            <el-select
              :disabled="product.id != '' && product.id != undefined"
              v-model="product.specValue"
              style="width: 100%;"
              class="m-2"
              placeholder="选择规格"
              size="default"
              @change="changeSpecValueList"
            >
              <el-option
                v-for="item in productSpecList"
                :key="item.specValue"
                :label="item.specName"
                :value="item.specValue"
              />
            </el-select>
          </el-form-item>

          <div
            class="specValue"
            v-for="(item, index) in specValueList"
            :key="index"
          >
            <span class="tag-group__title">{{ item.key }}</span>
            <el-tag
              class="tag-group__title"
              type="success"
              effect="dark"
              v-for="(specValue, index) in item.valueList"
              :key="index"
            >
              {{ specValue }}
            </el-tag>
          </div>

          <el-form-item label="商品SKU">
            <el-table :data="product.productSkuList" border style="width: 100%">
              <el-table-column prop="skuSpec" label="规格" width="180" />
              <el-table-column label="图片" #default="scope" width="80">
                <el-upload
                  class="avatar-uploader"
                  action="http://localhost:8501/admin/system/fileUpload"
                  :show-file-list="false"
                  :on-success="
                    (response, uploadFile, fileList) =>
                      handleSkuSuccess(
                        response,
                        uploadFile,
                        fileList,
                        scope.row
                      )
                  "
                  :headers="headers"
                >
                  <img
                    v-if="scope.row.thumbImg"
                    :src="scope.row.thumbImg"
                    class="avatar"
                  />
                  <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                  </el-icon>
                </el-upload>
              </el-table-column>
              <el-table-column label="售价" #default="scope">
                <el-input v-model="scope.row.salePrice" />
              </el-table-column>
              <el-table-column label="市场价" #default="scope">
                <el-input v-model="scope.row.marketPrice" />
              </el-table-column>
              <el-table-column label="成本价" #default="scope">
                <el-input v-model="scope.row.costPrice" />
              </el-table-column>
              <el-table-column label="库存数" #default="scope">
                <el-input v-model="scope.row.stockNum" />
              </el-table-column>
              <el-table-column label="重量" #default="scope">
                <el-input v-model="scope.row.weight" />
              </el-table-column>
              <el-table-column label="体积" #default="scope">
                <el-input v-model="scope.row.volume" />
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-collapse-item>
        <el-collapse-item title="商品详情信息" name="productDetails">
          <el-form-item label="详情图片">
            <el-upload
              v-model:file-list="detailsFileList"
              action="http://localhost:8501/admin/system/fileUpload"
              list-type="picture-card"
              multiple
              :on-success="handleDetailsSuccess"
              :on-remove="handleDetailsRemove"
              :headers="headers"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-collapse-item>
        <el-collapse-item title="保存修改数据" name="submit" :disabled="true">
          <el-form-item>
            <el-button type="primary" @click="saveOrUpdate">提交</el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
          </el-form-item>
        </el-collapse-item>
      </el-collapse>
    </el-form>
  </el-dialog>

  <!--分页页码-->
  <el-pagination
    v-model:current-page="pageParams.page"
    v-model:page-size="pageParams.limit"
    :page-sizes="[10, 20, 50, 100]"
    layout="total, sizes, prev, pager, next"
    :total="total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { getProductPageAPI } from '@/api/product'
import { getListAPI } from '@/api/brand'
import { getSelectList } from '@/api/category'
import { getSelectAllAPI } from '@/api/productUnit'
import { getPageAPI } from '@/api/productSpec'
import { useApp } from '@/pinia/modules/app'
//====================查询======================================================
//数据展示数据模型
const list = ref([])
//搜索表单数据模型
const productDto = ref({
  brandId: '',
  categoryId: '',
})
//表单标题
const title = ref('')
// 分页条数据模型
const total = ref(0)

//分页条数据模型
const pageParamsForm = {
  page: 1, // 页码
  limit: 10, // 每页记录数
}
const pageParams = ref(pageParamsForm)
// 定义存储搜索表单品牌列表数据模型
const brandList = ref([])
// 定义存储添加表单品牌列表数据模型
const categoryBrandList = ref([])
//存储选择的分类ID列表数据模型
const searchCategoryIdList = ref([])
//定义存储商品单位id列表
const productUnitList = ref([])
//定义存储商品规格列表
const productSpecList = ref([])
// 分类树懒加载配置
const props = {
  lazy: true, // 启用懒加载
  value: 'id', // 绑定每个分类的id
  label: 'name', // 绑定每个分类的名称
  leaf: 'leaf', // 是否为叶子节点
  async lazyLoad(node, resolve) {
    //加载数据的方法
    if (typeof node.value == 'undefined') {
      node.value = 0
    }
    const { data } = await getSelectList(node.value) //查询商品分类菜单
    // 设置每个节点是否为叶子节点
    data.forEach(function(item) {
      //判断
      item.leaf = !item.hasChildren
    })
    //返回数据
    resolve(data)
  },
}
// 存储懒加载的配置
const categoryProps = ref(props)
//==============搜索按钮事件===============================
const fetchData = () => {
  getPageData()
}
//================重置按钮事件=================
const resetData = () => {
  productDto.value = {}
  searchCategoryIdList.value = []
  getPageData()
}
//============调用后端查询所有品牌接口=======================
const getListData = async () => {
  const { code, data, message } = await getListAPI()
  //搜索表单品牌id列表
  brandList.value = data
  //添加和修改表单品牌列表
  categoryBrandList.value = data
}
//===============调用后端查询商品接口========================================
const getPageData = async () => {
  const { code, data, message } = await getProductPageAPI(
    pageParams.value.page,
    pageParams.value.limit,
    productDto.value
  )
  list.value = data.list
  total.value = data.total
}
//================调用后端查询商品单位接口========================================
const getSelectAllData = async () => {
  const { code, data, message } = await getSelectAllAPI()
  //渲染商品单位数据
  productUnitList.value = data
}
//======================调用后端查询商品规格接口===================================
const getProductSpecPageData = async () => {
  const { code, data, message } = await getPageAPI(1, 100)
  console.log(data.list);
  //渲染商品规格数据
  productSpecList.value = data.list
}
onMounted(() => {
  //调用后端查询商品接口
  getPageData()
  //调用后端查询所有品牌接口
  getListData()
  //调用后端查询所有商品单位接口
  getSelectAllData()
  //调用后端查询所有商品规格接口
  getProductSpecPageData()
})
//=======================添加商品=================================================
//添加商品数据模型
const product = ref({
  id: '', //商品id
  name: '', //商品name
  categoryIdList: '', //存分类id列表
  brandId: '', //品牌id
  unitName: '', //商品单位name
  sliderUrls: '', //商品轮播图
  specValue: '', //选择规格
})
//控制添加和修该表单显示
const dialogVisible = ref(false)
//控制添加和修该表单标题
const addShow = () => {
  title.value = '添加表单'
  dialogVisible.value = true
}
//====================修改商品信息=========================================
const editShow = () => {
  title.value = '修改表单表单'
  dialogVisible.value = true
}
///////////////////////////////////////////////////////////////////////////////文件上传
// 从pinia中获取token，在进行文件上传的时候将token设置到请求头中
const headers = {
  token: useApp().authorization.token,
}

// 图像上传成功以后的事件处理函数

const handleSliderSuccess = (response, uploadFile) => {
  product.value.sliderUrls = response.data
}
</script>

<style scoped>
.search-div {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}

.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}

.tag-group__title {
  margin-right: 10px; /* 调整元素之间的水平间距 */
}

.specValue {
  margin-bottom: 10px;
  margin-top: 10px;
  font-size: 14px;
}

.avatar-uploader .avatar {
  width: 50px;
  height: 50px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 50px;
  height: 50px;
  text-align: center;
}
</style>
